<template>
  <!-- 值 -->
  <div class="px-4">
    <component
      :is="setComp(condValue.operator, condValue.rightType)"
      :cond-value="condValue.right"
      :mul="setMul(condValue.operator, condValue.rightType)"
      @value-change="valueChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, watch, inject } from 'vue';
import { EOperator, ERightType } from '../type';
import { ICondValue } from './type';

import CondValueInput from './InputValue/index.vue';
import CondValueSelect from './SelectValue/index.vue';
import CondValueTag from './TagValue/index.vue';
import CondValueNull from './NullValue/index.vue';
import { ExpValue } from './ExpValue';
import { conditionsKey } from '../data';

const { variableOptions } = inject(conditionsKey);
const props = defineProps<{
  rightType?: ERightType;
  operator?: EOperator;
  right?: string;
}>();
const emit = defineEmits(['delete', 'conjChange', 'condValueChange']);

// 值
const condValue = reactive<ICondValue>({ rightType: undefined, operator: undefined, right: '' });
// 设置值
const setCondValue = (operator?: EOperator, rightType?: ERightType, right?: string) => {
  operator ? (condValue.operator = operator) : (condValue.operator = undefined);
  rightType ? (condValue.rightType = rightType) : (condValue.rightType = undefined);
  condValue.right = right || '';
};
setCondValue(props.operator, props.rightType, props.right);

watch(
  [() => props.rightType, () => props.operator, () => props.right, () => variableOptions],
  ([newRightType, newEOperator, newRight]) => {
    setCondValue(newEOperator, newRightType, newRight);
  },
  { deep: true }
);

// 设置是否多选
const setMul = (operator?: EOperator, rightType?: ERightType) => {
  let result = false;
  if (operator && rightType && rightType === ERightType.Variable && (operator === EOperator.In || operator === EOperator.NotIn)) {
    result = true;
  }
  return result;
};

// 设置组件
const setComp = (operator?: EOperator, rightType?: ERightType) => {
  if (!operator || !rightType) {
    return CondValueNull;
  }
  switch (operator) {
    case 'IN':
    case 'NOT_IN':
      switch (props.rightType) {
        case ERightType.Variable:
          return CondValueSelect;

        default:
          return CondValueTag;
      }

    default:
      switch (props.rightType) {
        case ERightType.Variable:
          return CondValueSelect;
          case ERightType.Expression:
            return ExpValue;
        default:
          return CondValueInput;
      }
  }
};

// 值
const valueChange = (val: any) => {
  emit('condValueChange', val);
};
</script>
